package org.etom.impl.connector.util;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.etom.impl.connector.Activator;

/**
 * An utility class which is responsible
 * for the common tasks.
 */
public abstract class Utility {
  
  private static String HEADER_KEY_USER_AGENT = "User-Agent";
  private static String HEADER_VAL_USER_AGENT = "EtoM";
  
  private Utility() {} //hide the class instances
  
  /**
   * The method copies the cookies
   * from the <code>source</code> to the <code>destination</code>.
   * 
   * @param source - the cookies are read from here
   * @param destination - the cookies are set here
   */
  public static void copyCookies(Map<?, ?> source, Map<String, String> destination) {
    if ((source == null) || (destination == null)) return;
    Iterator<?> keyIterator = source.keySet().iterator();
    Object currentKey;
    Object currentValue;
    StringBuffer cookies = new StringBuffer();
    while (keyIterator.hasNext()) {
      currentKey = keyIterator.next();
      currentValue = source.get(currentKey);
      if ("Set-Cookie".equals(currentKey)) {
        if (currentValue instanceof String) {
          String currentValStr = (String) currentValue;
          cookies.append(currentValStr.substring(0, currentValStr.indexOf(';')));
          cookies.append("; ");
        } else if (currentValue instanceof List<?>) {
          List<?> currentValList = (List<?>) currentValue;
          for (int i = 0; i < currentValList.size(); i++) {
            String currentValStr = (String) currentValList.get(i);
            cookies.append(currentValStr.substring(0, currentValStr.indexOf(';')));
            cookies.append("; ");
          }
        }
      }
    }
    if (cookies.length() != 0) {
      cookies.deleteCharAt(cookies.length() - 1); //remove " "
      cookies.deleteCharAt(cookies.length() - 1); //remove ;
      destination.put("Cookie", cookies.toString());
    }
  }
  
  /**
   * The method cares about the initial properties.
   * 
   * @return - the initial properties
   */
  public static Map<String, String> getInitialProperties() {
    String version = Activator.getDefault().getBundleVersion();
    Map<String, String> props = new Hashtable<String, String>();
    props.put(HEADER_KEY_USER_AGENT,
        HEADER_VAL_USER_AGENT + "/" + ((null != version) ? version : ""));
    return props;
  }
  
}
